package org.example.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.springboot.common.annotation.RateLimit;
import org.example.springboot.common.utils.Result;
import org.example.springboot.entity.FmcControl;
import org.example.springboot.entity.PendingTasks;
import org.example.springboot.entity.RationPendingTasks;
import org.example.springboot.service.FmcControlService;
import org.example.springboot.service.RationPendingTasksService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/mqtt")
public class MqttController {

    @Resource
    private FmcControlService fmcControlService;

    @Resource
    private RationPendingTasksService rationPendingTasksService;

    @PostMapping("/publish")
    public Result<String> sendMessage(@RequestBody FmcControl fmcControl) {
       return fmcControlService.sendMessageToMqtt(fmcControl);
    }

    /**
     * 一键启动
     */
    @PostMapping("/batchPublish")
    public Result<String> batchPublish(@RequestBody List<FmcControl> fmcControls) {
        OptionalInt minSort = fmcControls.stream()
                .mapToInt(FmcControl::getSort)
                .min();
        // 找到所有 sort 值等于最小值的对象集合
        List<FmcControl> minSortObjects = fmcControls.stream()
                .filter(fmc -> fmc.getSort() == minSort.orElse(Integer.MAX_VALUE))
                .collect(Collectors.toList());
        log.info("最小sort值对象集合: {}", minSortObjects);

        // 找到剩下的对象集合
        List<FmcControl> otherObjects = fmcControls.stream()
                .filter(fmc -> fmc.getSort() != minSort.orElse(Integer.MAX_VALUE))
                .collect(Collectors.toList());
        log.info("其他对象集合: {}", otherObjects);
        for(FmcControl fmcControl : minSortObjects){
            fmcControlService.sendMessageToMqtt(fmcControl);
        }
        //剩下的保存到待执行任务中
        List<RationPendingTasks> rationPendingTasksList = new ArrayList<>();
        for(FmcControl fmcControl : otherObjects){
            RationPendingTasks rationPendingTasks = new RationPendingTasks();
            rationPendingTasks.setSort(fmcControl.getSort());
            rationPendingTasks.setMqttContent(JSONObject.toJSONString(fmcControl));
            rationPendingTasksList.add(rationPendingTasks);
        }
        rationPendingTasksService.saveBatch(rationPendingTasksList);
        return Result.ok();
    }
}
